package com.example.aijava.controller;

import com.example.aijava.dto.*;
import com.example.aijava.model.User;
import com.example.aijava.qiniuyun.QiniuAiService;
import com.example.aijava.service.UserService;
import com.example.aijava.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    @Autowired
    public AuthController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    // 注册接口：返回UserDTO
    @PostMapping("/register")
    public Response register(@RequestBody RegisterRequest request) {
        User user = userService.register(request);
        String token = jwtUtil.generateToken(user.getUsername());
       // return new Response(true, "注册成功", user, token);
        return new Response(true, "注册成功", UserDTO.fromUser(user), token);
    }
    // 登录接口：返回UserDTO
    @PostMapping("/login")
    public Response login(@RequestBody LoginRequest request) {
        String token = userService.login(request);
        User user = userService.getProfile(request.getUsername());
        // 返回 UserDTO，统一数据格式
        return new Response(true, "登录成功", UserDTO.fromUser(user), token);
    }
    // 获取个人信息：返回UserDTO
    @GetMapping("/profile")
    public Response getProfile(@RequestHeader("Authorization") String token) {
        // 校验 Token 前缀（避免空指针或格式错误）
        if (!token.startsWith("Bearer ")) {
            return new Response(false, "Token 格式错误（需以 Bearer 开头）", null, null);
        }
        String jwtToken = token.substring(7);
        String username = jwtUtil.extractUsername(jwtToken);
        User user = userService.getProfile(username);
        // 修复：返回 UserDTO 而非原始实体
        return new Response(true, "获取用户信息成功", UserDTO.fromUser(user), null);

    }
    @Autowired
    private QiniuAiService qiniuAiService;

    @PostMapping("/api/chat")
    public String chat(@RequestBody String userMessage) {
        return qiniuAiService.sendChatRequest(userMessage);
    }
 }
